package HTTP介绍

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// 一,查询
func testPost1() {
	path := "http://apis.juhe.cn/simpleWeather/query"
	Values := url.Values{}
	Values.Add("key", "087d7d10f700d20e27bb753cd806e40b")
	Values.Add("city", "北京")
	r, err := http.PostForm(path, Values)
	if err != nil {
		log.Fatal(err)
	}
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	fmt.Println(string(b))
}

// 二,文本格式
func testPost2() {
	path := "http://httpbin.org/post"
	Values := url.Values{
		"key":  {"老郭"},
		"city": {"5001"},
	}
	redpBoby := Values.Encode()
	r, err := http.Post(path, "text/html", strings.NewReader(redpBoby))
	if err != nil {
		log.Fatal(err)
	}
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	fmt.Println(string(b))
}

// 三，json格式
func testPost3() {
	data := make(map[string]interface{})
	data["siye"] = "www/duoke360.com"
	data["name"] = "多课网"
	bytedata, _ := json.Marshal(data)

	r, err := http.Post("http://httpbin.org/post", "application/json", bytes.NewReader(bytedata))
	if err != nil {
		log.Fatal(err)
	}
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	fmt.Println(string(b))
}

// 四，自定义客户端
func testPost4() {
	client := http.Client{
		Timeout: time.Second * 5,
	}
	url := "http://apis.juhe.cn/simpleWeather/query?city=北京&key=087d7d10f700d20e27bb753cd806e40b"
	request, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		log.Fatal(err)
	}
	request.Header.Add("referer", "http://apis.juhe.cn/")
	res, err1 := client.Do(request)
	if err1 != nil {
		log.Fatal(err1)
	}
	defer res.Body.Close()
	b, _ := ioutil.ReadAll(res.Body)
	fmt.Println(string(b))
}

//五、实现 HTTP Server

func testHttpServer() {
	//请求处理函数
	f := func(resp http.ResponseWriter, req *http.Request) {
		io.WriteString(resp, "Hello World")
	}

	//响应路径，注意前面有斜杠 /
	http.HandleFunc("/hello", f)

	//设置监听端口，并监听，注意前面要有冒号 :
	err := http.ListenAndServe(":9999", nil)
	if err != nil {
		log.Fatal(err)
	}
}

// 六、使用Handler实现并发处理
/*type countHandler struct {
	mu sync.Mutex
	n  int
}

func (h *countHandler) ServerHttp(w http.ResponseWriter, r *http.Request) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.n++
	fmt.Fprintf(w, "count is %d\n", h.n)
}
func testHttpServer2() {
	http.Handle("/count", new(countHandler))
	log.Fatal(http.ListenAndServe(":9999", nil))
}*/
